package com.leyou.user.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import com.leyou.user.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author huangxin
 * @date 2019/5/11-10:54
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate template;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "user:verify:phone:";

    /**
     * 验证用户名或手机号是否存在
     *
     * @param data
     * @param type
     * @return
     */
    public boolean checkData(String data, Integer type) {
        User user = new User();
        //判断数据类型
        if (type == 1) {
            user.setUsername(data);
        } else if (type == 2) {
            user.setPhone(data);
        } else {
            throw new LyException(ExceptionEnum.INVALID_USER_DATA_TYPE);
        }
        int count = userMapper.selectCount(user);
        return count == 0;
    }


    /**
     * 发送验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);
        //生成key
        String key = KEY_PREFIX + phone;


        Map<String, String> map = new HashMap<>();
        map.put("phone", phone);
        map.put("code", code);

        template.convertAndSend("ly.sms.exchange", "sms.verify.code", map);


        //保存验证码,有效时间五分钟
        redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
    }

    @Transactional
    public void register(User user, String code) {
        //生成key
        String key = KEY_PREFIX + user.getPhone();
        //获取验证码
        String cacheCode = redisTemplate.opsForValue().get(key);
        //判断
        if (!StringUtils.equals(code,cacheCode)) {
            throw new LyException(ExceptionEnum.INVALID_VERIFY_CODE);
        }


        //加密
        user.setId(null);
        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        // 对密码进行加密
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        // 写入数据库
        user.setCreated(new Date());
        userMapper.insert(user);
    }

    public User query(String username,String password) {
        //根据用户名查询用户
        User condition = new User();
        condition.setUsername(username);
        User user = userMapper.selectOne(condition);
        //校验
        if (user==null){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //校验加密后的密码
        if (!StringUtils.equals(user.getPassword(),CodecUtils.md5Hex(password, user.getSalt()))){
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }

        //用户名和密码正确
        return user;
    }
}
